import React from 'react';
import JSXGraph from 'jsxgraph';
import {Row, Col, Slider, Button, Switch, Input} from 'antd';
import uiStore from '../store/uiStore';

import type1 from '../images/type_1.png';
import type2 from '../images/type_2.png';
import type3 from '../images/type_3.png';
import type4 from '../images/type_4.png';

const marks = {
  0: '0°C',
  25: '25°C',
  50: '50°C',
  75: '75°C',
  100: '100°C',
};

export  default class Curve extends React.Component {
  constructor(props) {
    super(props);

    console.log("curve constructor");
    this.state = {
      board: null,
      curve: null,
      points: [],
      height: 15,
      width: 15,
      bend: 40
    };
  }

  componentDidMount() {
    console.log("curve component did mount");
    this.draw();
  }

  draw() {
    const {setWidth, setHeight, zoomIn, zoomOut, generateModel, update3Dmodel} = uiStore;

    this.state.board = JXG.JSXGraph.initBoard('jxgbox', {boundingbox: [-15, 15, 1, -1], keepaspectratio: true,
                                                         axis: true, showCopyright:false,
                                                         showNavigation: true });

    uiStore._setHeight = (height) => {
      var bbox = this.state.board.getBoundingBox();
      bbox[1] = height;
      this.state.board.setBoundingBox(bbox);
    };

    uiStore._setWidth = (width) => {
      var bbox = this.state.board.getBoundingBox();
      bbox[0] = -1 * width;
      this.state.board.setBoundingBox(bbox);
    };

    uiStore._zoomIn = () => {
      this.state.board.zoomIn(0, 0);
      var bbox = this.state.board.getBoundingBox();
      this.setState({height: bbox[1], width: bbox[0]*-1});
    };
    uiStore._zoomOut = () => {
      this.state.board.zoomOut(0, 0);
      var bbox = this.state.board.getBoundingBox();
      this.setState({height: bbox[1], width: bbox[0]*-1});
    };

    this.state.board.suspendUpdate();
    var col = 'red';
    this.state.points.push(this.state.board.create('point',[0,9],{strokeColor:col,fillColor:col}));        // data point
    this.state.points.push(this.state.board.create('point',[-2,8],{strokeColor:col,fillColor:col}));       // data point
    this.state.points.push(this.state.board.create('point',[-3,6],{strokeColor:col,fillColor:col}));       // data point
    this.state.points.push(this.state.board.create('point',[-2,4],{strokeColor:col,fillColor:col}));       // data point
    this.state.points.push(this.state.board.create('point',[-3,2],{strokeColor:col,fillColor:col}));       // data point
    this.state.points.push(this.state.board.create('point',[-4,0],{strokeColor:col,fillColor:col}));       // data point

    this.state.curve = this.state.board.create('curve', JXG.Math.Numerics.bspline(this.state.points, 4), {strokecolor:'blue', strokeOpacity:0.6, strokeWidth:5});
    this.state.board.unsuspendUpdate();

    localStorage.setItem('points', JSON.stringify(this.getPointsXY()));

    this.state.points.forEach(function(ele){
      ele.on('mouseup', (e)=> {
        let points = JSON.parse(localStorage.getItem('points'));
        for (var i=0;i<points.length;i++) {
          if (ele.id === points[i].id) {
            points[i].x = Math.round(ele.X());
            points[i].y = Math.round(ele.Y());
            break;
          }
        }
        localStorage.setItem('points', JSON.stringify(points));
        generateModel();
      });
    });
  }

  addPoint() {
    console.log("add point");
    console.log(this.state.points);
    this.state.board.suspendUpdate();
    let p = this.state.board.create('point',[Math.random()*2-1,Math.random()*2-1],
                      {strokeColor:'red',fillColor:'red'});
    p.on('mouseup', (e)=> {
      let points = JSON.parse(localStorage.getItem('points'));
      for (var i=0;i<points.length;i++) {
        if (p.id === points[i].id) {
          points[i].x = Math.round(p.X());
          points[i].y = Math.round(p.Y());
          break;
        }
      }
      localStorage.setItem('points', JSON.stringify(points));
      uiStore.generateModel();
    });
    this.state.points.push(p);
    this.state.board.unsuspendUpdate();

    const {setWidth, setHeight, zoomIn, zoomOut, generateModel, update3Dmodel} = uiStore;
    localStorage.setItem('points', JSON.stringify(this.getPointsXY()));
    uiStore.generateModel();
  }

  deletePoint() {
    console.log("delete point");
    this.state.board.suspendUpdate();

    if (this.state.points.length>2) {
      this.state.board.removeObject(this.state.points[this.state.points.length-1]);  // remove the last point from the list of objects
      this.state.points.splice(this.state.points.length-1,1);           // remove the last point from the point array.
    }
    this.state.board.unsuspendUpdate();

    const {setWidth, setHeight, zoomIn, zoomOut, generateModel, update3Dmodel} = uiStore;
    localStorage.setItem('points', JSON.stringify(this.getPointsXY()));
    uiStore.generateModel();
  }

  getPointsXY() {
    let pointsXY = [];
    for (var i=0; i<this.state.points.length; i++) {
      pointsXY.push({id: this.state.points[i].id ,
                     x: Math.round(this.state.points[i].X()),
                     y: Math.round(this.state.points[i].Y())});
    }

    return pointsXY;
  }

  render() {

    console.log("curve render");
    const height = this.state.height;
    const width = this.state.width;
    const bend = this.state.bend;
    const {setWidth, setHeight, zoomIn, zoomOut, generateModel} = uiStore;

    if (this.state.board) {
      setWidth(width);
      setHeight(height);
    }

    return (
      <div>
        <div className="line">
          <div id="jxgbox" className="jxgbox" style={{width: 358, height: 358}}></div>
        </div>
        <div className="size">
            <div className="sizeControl">
                <p>Height (mm)</p>
                <div className="form">
                    <Input type="text" name="name" value={height} />
                    <div onClick={(e) => this.setState(Object.assign({}, this.state, {height: height+1}))} className="btm">+</div>
                    <div onClick={(e) => this.setState(Object.assign({}, this.state, {height: height-1}))} className="btm">-</div>
                </div>
            </div>
            <div className="sizeControl">
                <p>Width (mm)</p>
                <div className="form">
                    <Input type="text" name="name" value={width} />
                    <div onClick={(e) => this.setState(Object.assign({}, this.state, {width: width+1}))} className="btm">+</div>
                    <div onClick={(e) => this.setState(Object.assign({}, this.state, {width: width-1}))} className="btm">-</div>
                </div>
            </div>
        </div>
        <div className="point">
            <div className="zoom">
                <p>Point</p>
                <div onClick={() => this.addPoint()} className="btm">+</div>
                <div onClick={() => this.deletePoint()} className="btm">-</div>
            </div>
            <div className="zoom">
                <p >Zoom</p>
                <div onClick={() => zoomIn()} className="btm">+</div>
                <div onClick={() => zoomOut()} className="btm">-</div>
            </div>
        </div>
        <div className="size">
          <div><p>Bend</p></div>
          <div style={{padding: 5}}>
          <Slider marks={marks} value={bend}
            onChange={(v) => this.setState(Object.assign({}, this.state, {bend: v}))} />
          </div>
          <br />
          <Row type="flex" justify="space-between" align="middle">
            <Col span={3}>
              <Button
                style={{backgroundColor: '#ff6c00', color: 'white', borderColor: '#ff6c00'}}
                onClick={(e) => this.setState(Object.assign({}, this.state, {bend: bend-1}))}
                type="ghost" shape="circle" icon="minus" />
            </Col>
            <Col span={3}>
              <Button
                style={{backgroundColor: '#ff6c00', color: 'white', borderColor: '#ff6c00'}}
                onClick={(e) => this.setState(Object.assign({}, this.state, {bend: bend+1}))}
                type="ghost" shape="circle" icon="plus" />
            </Col>
          </Row>
        </div>

      </div>
    );
  }
}
